<template>
  <div class="app-container">
    <!-- 新增关联基团按钮 -->
    <el-button 
      type="primary" 
      icon="el-icon-plus" 
      size="small" 
      style="margin-bottom: 15px;"
      @click="handleAddGroup"
    >
      新增关联基团
    </el-button>

    <!-- 基本信息卡片 -->
    <el-card shadow="never" style="margin-bottom: 20px;">
      <div slot="header" class="clearfix">
        <span style="font-weight: bold; color: #409EFF;">基本信息</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="info-item">
            <span class="info-label">成分编号：</span>
            <span class="info-value">{{ baseInfo.constituentNo || '-' }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="info-item">
            <span class="info-label">成分名称：</span>
            <span class="info-value">{{ baseInfo.constituentName || '-' }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="info-item">
            <span class="info-label">创建人：</span>
            <span class="info-value">{{ baseInfo.creator || '-' }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="info-item">
            <span class="info-label">创建时间：</span>
            <span class="info-value">{{ baseInfo.createTime || '-' }}</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 关联基团列表卡片 -->
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span style="font-weight: bold; color: #409EFF;">关联基团列表</span>
      </div>

      <el-table v-loading="loading" :data="detailList" style="width: 100%">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="基团编号" align="center" prop="groupNo" width="120" />
        <el-table-column label="基团名称" align="center" prop="groupName" width="120" />
        <el-table-column label="基团符号" align="center" prop="groupSymbol" width="120" />
        <el-table-column label="振动类型" align="center" prop="vibrationType" width="120" />
        <el-table-column label="波长范围/nm" align="center" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.startWavelength }}-{{ scope.row.endWavelength }}</span>
          </template>
        </el-table-column>
        <el-table-column label="波数范围/cm^-1" align="center" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.startWavenumber }}-{{ scope.row.endWavenumber }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remarks" min-width="120" />
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              style="color: #F56C6C;"
              @click="handleDeleteGroup(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 关联基团选择器对话框 -->
    <el-dialog title="选择关联基团" :visible.sync="open" width="800px" append-to-body>
      <!-- 搜索区域 -->
      <el-form :model="groupQueryParams" ref="groupQueryForm" size="small" :inline="true" label-width="80px" style="margin-bottom: 20px;">
        <el-form-item label="基团编号" prop="groupNo">
          <el-input
            v-model="groupQueryParams.groupNo"
            placeholder="请输入基团编号"
            clearable
            @keyup.enter.native="handleGroupQuery"
            style="width: 150px;"
          />
        </el-form-item>
        <el-form-item label="基团名称" prop="groupName">
          <el-input
            v-model="groupQueryParams.groupName"
            placeholder="请输入基团名称"
            clearable
            @keyup.enter.native="handleGroupQuery"
            style="width: 150px;"
          />
        </el-form-item>
        <el-form-item label="基团符号" prop="groupSymbol">
          <el-input
            v-model="groupQueryParams.groupSymbol"
            placeholder="请输入基团符号"
            clearable
            @keyup.enter.native="handleGroupQuery"
            style="width: 150px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleGroupQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetGroupQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 基团列表 -->
      <el-table 
        v-loading="groupLoading" 
        :data="groupList" 
        @selection-change="handleGroupSelectionChange"
        style="width: 100%;"
        height="350px"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="基团编号" align="center" prop="groupNo" width="120" />
        <el-table-column label="基团名称" align="center" prop="groupName" width="120" />
        <el-table-column label="基团符号" align="center" prop="groupSymbol" width="100" />
        <el-table-column label="振动类型" align="center" prop="vibrationType" width="120" />
        <el-table-column label="波长范围/nm" align="center" width="130">
          <template slot-scope="scope">
            <span>{{ scope.row.startWavelength }}-{{ scope.row.endWavelength }}</span>
          </template>
        </el-table-column>
        <el-table-column label="波数范围/cm^-1" align="center" width="130">
          <template slot-scope="scope">
            <span>{{ scope.row.startWavenumber }}-{{ scope.row.endWavenumber }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remarks" min-width="100" />
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="groupTotal > 0"
        :total="groupTotal"
        :page.sync="groupQueryParams.pageNum"
        :limit.sync="groupQueryParams.pageSize"
        @pagination="getGroupList"
        style="margin-top: 15px;"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmGroupSelection" :disabled="selectedGroups.length === 0">确 定（已选{{ selectedGroups.length }}项）</el-button>
        <el-button @click="cancelGroupSelection">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDetail, getDetail, delDetail, addDetail, updateDetail } from "@/api/constituent/detail";
import { listGroup } from "@/api/constituent/group";

export default {
  name: "Detail",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 成分明细列表数据
      detailList: [],
      // 基本信息
      baseInfo: {
        constituentId: null,
        constituentNo: null,
        constituentName: null,
        creator: null,
        createTime: null
      },
      // 是否显示弹出层
      open: false,
      
      // 基团选择器相关
      groupLoading: false,
      groupList: [],
      groupTotal: 0,
      selectedGroups: [],
      groupQueryParams: {
        pageNum: 1,
        pageSize: 10,
        groupNo: null,
        groupName: null,
        groupSymbol: null
      }
    };
  },
  created() {
    this.parseQueryParams();
    this.getList();
  },
  methods: {
    /** 解析查询参数 */
    parseQueryParams() {
      if (this.$route.query.baseInfo) {
        try {
          const baseInfo = JSON.parse(this.$route.query.baseInfo);
          this.baseInfo = { ...this.baseInfo, ...baseInfo };
        } catch (error) {
          console.error('解析baseInfo参数失败:', error);
        }
      }
    },
    /** 查询成分明细列表 */
    getList() {
      if (!this.baseInfo.constituentId) {
        console.warn('没有成分ID，无法查询明细列表');
        this.loading = false;
        return;
      }

      this.loading = true;
      const queryParams = {
        constituentId: this.baseInfo.constituentId
      };
      
      listDetail(queryParams).then(response => {
        this.detailList = response.rows || [];
        this.loading = false;
      }).catch(error => {
        console.error('查询成分明细列表失败:', error);
        this.loading = false;
      });
    },
    
    /** 新增关联基团 - 打开选择器 */
    handleAddGroup() {
      this.open = true;
      this.resetGroupQuery();
      this.getGroupList();
    },
    
    /** 查询基团列表 */
    getGroupList() {
      this.groupLoading = true;
      listGroup(this.groupQueryParams).then(response => {
        this.groupList = response.rows || [];
        this.groupTotal = response.total || 0;
        this.groupLoading = false;
      }).catch(error => {
        console.error('查询基团列表失败:', error);
        this.groupLoading = false;
      });
    },
    
    /** 基团搜索 */
    handleGroupQuery() {
      this.groupQueryParams.pageNum = 1;
      this.getGroupList();
    },
    
    /** 重置基团搜索 */
    resetGroupQuery() {
      this.groupQueryParams = {
        pageNum: 1,
        pageSize: 10,
        groupNo: null,
        groupName: null,
        groupSymbol: null
      };
      this.selectedGroups = [];
      this.$refs.groupQueryForm && this.$refs.groupQueryForm.resetFields();
    },
    
    /** 基团选择变化 */
    handleGroupSelectionChange(selection) {
      this.selectedGroups = selection;
    },
    
    /** 确认选择基团 */
    confirmGroupSelection() {
      if (this.selectedGroups.length === 0) {
        this.$modal.msgWarning('请选择要关联的基团');
        return;
      }
      
      // 批量添加关联关系
      const promises = this.selectedGroups.map(group => {
        const detailData = {
          constituentId: this.baseInfo.constituentId,
          constituentNo: this.baseInfo.constituentNo,
          constituentName: this.baseInfo.constituentName,
          groupId: group.groupId,
          groupNo: group.groupNo,
          groupName: group.groupName,
          groupSymbol: group.groupSymbol,
          vibrationType: group.vibrationType,
          startWavelength: group.startWavelength,
          endWavelength: group.endWavelength,
          startWavenumber: group.startWavenumber,
          endWavenumber: group.endWavenumber,
          remarks: group.remarks
        };
        return addDetail(detailData);
      });
      
      Promise.all(promises).then(() => {
        this.$modal.msgSuccess(`成功关联${this.selectedGroups.length}个基团`);
        this.open = false;
        this.getList(); // 重新加载列表
      }).catch(error => {
        console.error('关联基团失败:', error);
        this.$modal.msgError('关联基团失败，请重试');
      });
    },
    
    /** 取消选择基团 */
    cancelGroupSelection() {
      this.open = false;
      this.resetGroupQuery();
    },
    
    /** 删除基团 */
    handleDeleteGroup(row) {
      this.$modal.confirm('是否确认删除该关联基团？').then(() => {
        return delDetail(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.info-item {
  margin-bottom: 10px;
}

.info-label {
  color: #606266;
  font-weight: bold;
}

.info-value {
  color: #303133;
  margin-left: 8px;
}
</style>
